package com.shiyingzi.security.controller;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
//import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.gson.Gson;
import com.shiyingzi.auser.model.AChannel;
import com.shiyingzi.auser.model.AUser;
import com.shiyingzi.auser.service.AChannelService;
import com.shiyingzi.auser.service.AUserService;
import com.shiyingzi.dictionary.model.Dictionary;
import com.shiyingzi.dictionary.service.IDictionaryService;
import com.shiyingzi.gw.dao.NewsMapper;
import com.shiyingzi.gw.dao.ProductMapper;
import com.shiyingzi.gw.model.News;
import com.shiyingzi.gw.model.Product;
import com.shiyingzi.gw.model.ProductType;
import com.shiyingzi.gw.model.Setting;
import com.shiyingzi.gw.service.NewsService;
import com.shiyingzi.gw.service.ProductService;
import com.shiyingzi.gw.service.ProductTypeService;
import com.shiyingzi.gw.service.SettingService;
import com.shiyingzi.product.model.AppABasicInformation;
import com.shiyingzi.product.model.AppBOccupational;
import com.shiyingzi.product.model.AppCIncomeAndLiability;
import com.shiyingzi.product.model.AppDContactInformation;
import com.shiyingzi.product.model.AppEBorrowerInformation;
import com.shiyingzi.product.model.AppFHouseProperty;
import com.shiyingzi.product.model.AppGWorkInformation;
import com.shiyingzi.product.model.AppHPolicyInformation;
import com.shiyingzi.product.model.AppIImpPath;
import com.shiyingzi.product.service.AppABasicInformationService;
import com.shiyingzi.product.service.AppBOccupationalService;
import com.shiyingzi.product.service.AppCIncomeAndLiabilityService;
import com.shiyingzi.product.service.AppDContactInformationService;
import com.shiyingzi.product.service.AppEBorrowerInformationService;
import com.shiyingzi.product.service.AppFHousePropertyService;
import com.shiyingzi.product.service.AppGWorkInformationService;
import com.shiyingzi.product.service.AppHPolicyInformationService;
import com.shiyingzi.product.service.AppIImpPathService;
import com.shiyingzi.security.dao.UserDao;
import com.shiyingzi.security.model.Menu;
import com.shiyingzi.security.model.Role;
import com.shiyingzi.security.model.User;
import com.shiyingzi.security.service.ISecurityUserService;

@Controller
public class SecurityViewController {

	@Value("${web.upload-path}")
    private String staticUploadPath;
	
	@Autowired
	private ProductMapper productMapper;

	@Resource(name = ISecurityUserService.BEAN_ID)
	private ISecurityUserService securityService;
	@Resource(name = IDictionaryService.BEAN_ID)
	private IDictionaryService dictionaryService;
	
	@Resource(name = AppABasicInformationService.BEAN_ID)
	private AppABasicInformationService appABasicInformationService;
	
	@Resource(name = AppBOccupationalService.BEAN_ID)
	private AppBOccupationalService appBOccupationalService;
	
	@Resource(name = AppDContactInformationService.BEAN_ID)
	private AppDContactInformationService appDContactInformationService;
	
	@Resource(name = AppCIncomeAndLiabilityService.BEAN_ID)
	private AppCIncomeAndLiabilityService appCIncomeAndLiabilityService;
	
	@Resource(name = AppEBorrowerInformationService.BEAN_ID)
	private AppEBorrowerInformationService appEBorrowerInformationService;
	
	@Resource(name = AppFHousePropertyService.BEAN_ID)
	private AppFHousePropertyService appFHousePropertyService;
	
	@Resource(name = AppGWorkInformationService.BEAN_ID)
	private AppGWorkInformationService appGWorkInformationService;
	
	@Resource(name = AppHPolicyInformationService.BEAN_ID)
	private AppHPolicyInformationService appHPolicyInformationService;
	
	@Resource(name = AUserService.BEAN_ID)
	private AUserService aUserService;
	
	@Resource(name = AppIImpPathService.BEAN_ID)
	private AppIImpPathService appIImpPathService;
	
	
	@Resource(name = SettingService.BEAN_ID)
	private SettingService settingService;
	
	@Resource(name = ProductService.BEAN_ID)
	private ProductService productService;
	
	@Resource(name = ProductTypeService.BEAN_ID)
	private ProductTypeService productTypeService;
	
	@Resource(name = NewsService.BEAN_ID)
	private NewsService newsService;
	
	
	@Resource(name = AChannelService.BEAN_ID)
	private AChannelService aChannelService;
	@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST })
	public String login(String url, Model model) {
		model.addAttribute("url", url);
		return "login";
	}

	@RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST })
	public String index(Model model) {
		List<Menu> listMenu = securityService.getMenusByCurrentUser();
		model.addAttribute("listMenu", listMenu);
		return "index";
	}

	@RequestMapping(value = "/main", method = { RequestMethod.GET, RequestMethod.POST })
	public String main(Model model) {
		return "main";
	}
	
	@RequestMapping(value = "/isetting", method = { RequestMethod.GET, RequestMethod.POST })
	public String setting(Model model) {
//		List<Menu> listMenu = securityService.getMenusByCurrentUser();
		Setting set =settingService.selectById(1);
		model.addAttribute("set", set);
		return "setting";
	}
	
	@RequestMapping(value = "/productView", method = { RequestMethod.GET, RequestMethod.POST })
	public String productView(Model model) {

		return "product";
	}
	
	
	@RequestMapping(value = "/newsView", method = { RequestMethod.GET, RequestMethod.POST })
	public String newsView(Model model) {

		return "news";
	}
	
	@RequestMapping(value = "/newsInfo", method = { RequestMethod.GET, RequestMethod.POST })
	public String newsInfo(Model model,Integer id) {
		News news = new News();
		if(id!=null){
			news=newsService.selectById(id);
		}
		model.addAttribute("news", news);
		return "news-info";
	}
	
	@RequestMapping(value = "/productInfo", method = { RequestMethod.GET, RequestMethod.POST })
	public String productInfo(Model model,Integer id) {
		Product product = new Product();
		if(id!=null){
			product=productService.selectById(id);
		}
		model.addAttribute("product", product);
		return "gw_product-info";
	}
	
	@RequestMapping(value = "/demo", method = { RequestMethod.GET, RequestMethod.POST })
	public String demo(Model model,Integer id) {
		
		return "demo";
	}
	
	@RequestMapping(value = "/newsEdit", method = { RequestMethod.GET, RequestMethod.POST })
	public String news(Model model,Integer id) {
		News news =new  News();
		if(id!=null){
			news=newsService.selectById(id);
		}
		model.addAttribute("news", news);
		return "news_edit";
	}
	
	
	@RequestMapping(value = "/productEdit", method = { RequestMethod.GET, RequestMethod.POST })
	public String productEdit(Model model,Integer id) {
		Product pro =new Product();
		if(id!=null){
			pro= productService.selectById(id);
		}
		
		List<ProductType> typelist = productTypeService.selectList(new EntityWrapper());
		
		model.addAttribute("pro", pro);
		model.addAttribute("typelist", typelist);
		return "product_edit";
	}

	@RequestMapping(value = "/table", method = { RequestMethod.GET, RequestMethod.POST })
	public String table(Model model) {
		return "table";
	}

	@RequestMapping(value = "/form", method = { RequestMethod.GET, RequestMethod.POST })
	public String form(Model model) {
		return "form";
	}

	@RequestMapping(value = "/user", method = { RequestMethod.GET, RequestMethod.POST })
	public String User(Model model) {
		return "user";
	}

	@RequestMapping(value = "/user_edit", method = { RequestMethod.GET, RequestMethod.POST })
	public String UserEdit(Integer id, Model model) {
		User user = new User();
		List<Role> rolesByUser = new ArrayList<>();
		if(id != null){
			user = securityService.getUserById(id);
			rolesByUser = securityService.getRolesByUser(user);
		}
		model.addAttribute("mUser", user);
		model.addAttribute("allRoles", securityService.getAllRoles());
		model.addAttribute("userRole", rolesByUser);
		return "user_edit";
	}

	@RequestMapping(value = "/menu", method = { RequestMethod.GET, RequestMethod.POST })
	public String Menu(Model model) {
		return "menu";
	}

	@RequestMapping(value = "/Menu_edit", method = { RequestMethod.GET, RequestMethod.POST })
	public String MenuEdit(Integer id, Model model) {
		Menu menu = new Menu();
		if(id != null){
			menu = securityService.getMenuById(id);
		}
		model.addAttribute("modifyMenu", menu);
		List<Menu> menusByCurrentUser = securityService.getMenusByCurrentUser();
		model.addAttribute("menusByCurrentUser", menusByCurrentUser);
		return "menu_edit";
	}

	@RequestMapping(value = "/role", method = { RequestMethod.GET, RequestMethod.POST })
	public String Role(Model model) {
		return "role";
	}

	@RequestMapping(value = "/role_edit", method = { RequestMethod.GET, RequestMethod.POST })
	public String RoleEdit(Integer id, Model model) {
		Role role = new Role();
		if(id != null){
			role = securityService.getRoleById(id);
		}
		model.addAttribute("mRole", role);
		return "role_edit";
	}

	@RequestMapping(value = "/role_authorize", method = { RequestMethod.GET, RequestMethod.POST })
	public String RoleAuthorize(int id, Model model) {
		List<Menu> allMenu = securityService.getAllMenuByRoleId(id);
		model.addAttribute("listMent", allMenu);
		return "role_authorize";
	}

	@RequestMapping(value = "/dictionary", method = { RequestMethod.GET, RequestMethod.POST })
	public String Dictionary(Model model) {
		return "dictionary";
	}

	@RequestMapping(value = "/dictionary_edit", method = { RequestMethod.GET, RequestMethod.POST })
	public String DictionaryEdit(Integer id, Model model) {
		Dictionary dic = new Dictionary();
		if(id != null){
			dic = dictionaryService.getDictionaryById(id);
		}
		model.addAttribute("mdic", dic);
		return "dictionary_edit";
	}
	
	@RequestMapping(value = "/a_product", method = { RequestMethod.GET, RequestMethod.POST })
	public String AProduct(Model model) {
		return "a_product";
	}
	@RequestMapping(value = "/a_product_editstate", method = { RequestMethod.GET, RequestMethod.POST })
	public String Producteditstate(Integer id,Model model) {
		AppABasicInformation code = new  AppABasicInformation();
		if(id !=null){
			code=appABasicInformationService.getProductById(id);
		}
		model.addAttribute("mUser", code);
		return "a_product_editstate";
	}
	@RequestMapping(value = "/a_product_edit", method = { RequestMethod.GET, RequestMethod.POST })
	public String ProductEdit(Integer id, Model model) {
		AppABasicInformation code = new AppABasicInformation();
		AppBOccupational abo= new AppBOccupational();
		AppCIncomeAndLiability aci= new AppCIncomeAndLiability();
		List<AppDContactInformation> appdc=new ArrayList<AppDContactInformation>();
		AppEBorrowerInformation aev=new AppEBorrowerInformation();
		AppFHouseProperty afh=new AppFHouseProperty();
		AppGWorkInformation agw=new AppGWorkInformation();
		AppHPolicyInformation ahp=new AppHPolicyInformation();
		List<AppIImpPath> aip=new ArrayList<AppIImpPath>();
		if(id !=null){
			code=appABasicInformationService.getProductById(id);
			abo=appBOccupationalService.getProductByAppAId(code.getId());
			aci=appCIncomeAndLiabilityService.getProductByAppAId(code.getId());
			appdc=appDContactInformationService.getAppDContactInformationByAppAId(code.getId());
			aev=appEBorrowerInformationService.getProductByAppAId(code.getId());
			afh=appFHousePropertyService.getProductByAppAId(code.getId());
			agw=appGWorkInformationService.getProductByAppAId(code.getId());
			ahp=appHPolicyInformationService.getProductByAppAId(code.getId());
			aip=appIImpPathService.getAppIImpPathByAppAId(id);
			code.setAbo(abo);
			code.setAcial(aci);
			code.setAebi(aev);
			code.setAfhp(afh);
			code.setAgwi(agw);
			code.setAhpi(ahp);
			code.setAip(aip);
		}
		model.addAttribute("mUser", code);
		model.addAttribute("appdc", appdc);
		model.addAttribute("aip", aip);
		return "a_product_edit";
	}
//	@RequestMapping(value = "/mobile/forms", method = { RequestMethod.GET, RequestMethod.POST })
//	public String Forms(Model model) {
//		return "forms";
//	}
	@RequestMapping(value = "/a_login", method = { RequestMethod.GET, RequestMethod.POST })
	public String ALogin(String url, Model model) {
		model.addAttribute("url", url);
		return "a_login";
	}
	@RequestMapping(value = "/a_register", method = { RequestMethod.GET, RequestMethod.POST })
	public String ARegister(String url, Model model) {
		model.addAttribute("url", url);
		List<AChannel> list=aChannelService.findlistBystate();
		model.addAttribute("list", list);
		return "a_register";
	}
	@RequestMapping(value = "/a_user", method = { RequestMethod.GET, RequestMethod.POST })
	public String FindAuser(Model model) {
		return "a_user";
	}
	@RequestMapping(value = "/a_user_edit", method = { RequestMethod.GET, RequestMethod.POST })
	public String AUserEdit(Integer id, Model model) {
		AUser code = new  AUser();
		if(id !=null){
			code=aUserService.getProductById(id);
		}
		List<AChannel> list=aChannelService.findlistBystate();
		model.addAttribute("mUser", code);
		model.addAttribute("list", list);
		return "a_user_edit";
	}
	@RequestMapping(value = "/a_user_uppwd", method = { RequestMethod.GET, RequestMethod.POST })
	public String AUserUppwd(Integer id, Model model) {
		AUser code = new  AUser();
		if(id !=null){
			code=aUserService.getProductById(id);
		}
		model.addAttribute("mUser", code);
		return "a_user_uppwd";
	}
	
	@RequestMapping(value = "/a_channel", method = { RequestMethod.GET, RequestMethod.POST })
	public String findAChannel(Model model) {
		return "a_channel";
	}
	@RequestMapping(value = "/a_channel_edit", method = { RequestMethod.GET, RequestMethod.POST })
	public String AChannelEdit(Integer id, Model model) {
		AChannel code = new  AChannel();
		if(id !=null){
			code=aChannelService.getAChannelById(id);
		}
		model.addAttribute("mUser", code);
		return "a_channel_edit";
	}
	@RequestMapping(value = "/user_uppwd", method = { RequestMethod.GET, RequestMethod.POST })
	public String UserUppwd(Integer id, Model model) {
		User code = new  User();
		if(id !=null){
			code=securityService.getUserById(id);
		}
		model.addAttribute("mUser", code);
		return "user_uppwd";
	}
	
	
	@RequestMapping(value = "/gw_index", method = { RequestMethod.GET, RequestMethod.POST })
	public String gw_index(Model model) {
		
		//查询最新产品
		List<Product> proList = productService.selectPage(new Page<Product>(1, 9)).getRecords();
		Setting set =settingService.selectById(1);
		model.addAttribute("set", set);
		model.addAttribute("proList", proList);
		
		List<News> newsList1 =newsService.selectPage(new Page<News>(1, 9)).getRecords();
		List<News> newsList2 =newsService.selectPage(new Page<News>(1, 9)).getRecords();
		//List<News> newsList3 =newsService.selectPage(new Page<News>(1, 9)).getRecords();
		
		int sum1 = productService.selectCount(new EntityWrapper<Product>().eq("type", 1));
		int sum2 = productService.selectCount(new EntityWrapper<Product>().eq("type", 2));
		int sum3 = productService.selectCount(new EntityWrapper<Product>().eq("type", 3));
		model.addAttribute("newsList1", newsList1);
		model.addAttribute("newsList2", newsList2);
//		model.addAttribute("sum1", sum1);
//		model.addAttribute("sum2", sum2);
//		model.addAttribute("sum3", sum3);
		//model.addAttribute("newsList3", newsList3);
		
		return "gw_index";
	}
	
	@RequestMapping(value = "/gw_news", method = { RequestMethod.GET, RequestMethod.POST })
	public String gw_news(Model model, Integer pageIndex) {

		Setting set =settingService.selectById(1);		
		List<News> newsList = newsService.selectPage(new Page<News>(1, 3)).getRecords();
		int sum = newsService.selectCount(null);

		model.addAttribute("news", newsList);
		model.addAttribute("set", set);
		model.addAttribute("sum", sum);
		
		return "gw_news";
	}
	
	@ResponseBody
	@RequestMapping(value = "/gw_news_page", method = { RequestMethod.GET, RequestMethod.POST })
	public String gw_news_page(Integer pageIndex) {
		List<News> newsList = newsService.selectPage(new Page<News>(pageIndex, 3)).getRecords();
		Gson gson= new Gson();
		String jsonStr = gson.toJson(newsList);
		return jsonStr;
	}
	
	@ResponseBody
	@RequestMapping(value = "/gw_product_page", method = { RequestMethod.GET, RequestMethod.POST })
	public String gw_product_page(Integer pageIndex, Integer typeIndex) {
		List<Product> proList = productService.selectPage(
				new Page<Product>(pageIndex, 4), new EntityWrapper<Product>().eq("type", typeIndex)).getRecords();
		
		Gson gson= new Gson();
		String jsonStr = gson.toJson(proList);
		return jsonStr;
	}

	@ResponseBody
	@RequestMapping(value = "/gw_product_sum", method = { RequestMethod.GET, RequestMethod.POST })
	public String gw_product_page(Integer typeIndex) {
		int sum = productService.selectCount(new EntityWrapper<Product>().eq("type", typeIndex));
		Gson gson= new Gson();
		String jsonStr = gson.toJson(sum);
		return jsonStr;
	}
	
	@RequestMapping(value = "/gw_example", method = { RequestMethod.GET, RequestMethod.POST })
	public String gw_example(Model model) {

		List<ProductType> typeList = new ArrayList<ProductType>();
		typeList = productTypeService.selectList(new EntityWrapper<>());
		Setting set =settingService.selectById(1);
		int sum1 = productService.selectCount(new EntityWrapper<Product>().eq("type", 1));

		model.addAttribute("set", set);
		model.addAttribute("sum1", sum1);
		model.addAttribute("typeList",typeList);

		return "gw_example";
	}
	
	
	@RequestMapping(value = "/upload")
	@ResponseBody
	public Map<String,String> upload(@RequestParam(value = "myFileName") MultipartFile file,
			HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String separator = System.getProperty("file.separator");

		System.out.println("staticUploadPath"+staticUploadPath);
		
		// 用于前端图片显示的路径 http://localhost:8080/upload/
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath() + separator + "upload" + separator;
		
		String uploadDir = staticUploadPath;

		byte[] bytes = null;
		try {

			bytes = file.getBytes();
			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				if (!dirPath.mkdirs()) {
				}
			}

			/**
			 * 构建新的图片名称
			 */
			String fileName = file.getOriginalFilename();
			int index = fileName.lastIndexOf(".");
			String extName = index > -1 ? fileName.substring(index) : ""; // .jpg
			String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
			String newFileName = uuid + extName;

			/**
			 * 保存图片至项目
			 */
			String filePath = staticUploadPath + newFileName;
			File descFile = new File(filePath);
			FileCopyUtils.copy(bytes, descFile);

			//map.put("data", basePath + newFileName);
			map.put("data",  newFileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(map.toString());
		return map;
	}
	
}
